package com.way2sms.way2inbox;

import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import www.way2inbox.adapter.SMSchatlistadapter;
import www.way2inbox.common.Constants;
import www.way2inbox.common.PrintMsg;
import www.way2inbox.data.Native_DatabaseHelper;
import www.way2inbox.data.SmsDatabase;
import www.way2inbox.data.item;
import www.way2inbox.data.smsfetch;
import www.way2inbox.settings.ApplicationConstants;
import www.way2inbox.settings.SettingsHeaderActivity;


public class Messages extends ActionBarActivity implements OnItemClickListener,
        View.OnClickListener, TextWatcher, View.OnTouchListener{

    RelativeLayout MessagesOverlay;
    ListView MessagesListview;
//    SMSListAdapter listAdapter;

    Dialog d;
    ListView MessageList;
    ArrayList<smsfetch> orinalConlist, smslist;
    private Filter contactFilter;
    SmsDatabase sms;
    Native_DatabaseHelper helper;
    List<smsfetch> allsms;
    ProgressDialog pd;
    String myPackageName,defaultSmsApp;
    boolean compatibleversion;
    myadapter listAdapter;
    // mainlayout declartion
    RelativeLayout MenuLayout_sub, MenuLayout_main, menu_search_edittext,
            Listview_Options;
    // main menu declartion
    RelativeLayout menu_search, menu_more_options, menu_newcompose;
    ImageView menuimage;
    // searchbox
    RelativeLayout menu_search_edit_back;
    EditText menu_search_Edittext;
    // sub menu
    RelativeLayout menu_private_sms, menu_spam_sms, menu_settings;
    // listview menu
    RelativeLayout Listview_back, Listview_delete, Listview_spam,
            Listview_private;
//default application layout
    RelativeLayout default_aplication;

    /*
    MenuLayout_main Options..
    RelativeLayout MenuLayout_main;
    RelativeLayout menu_search,menu_more_options,menu_newcompose;

    MenuLayout_sub;
    menu_private_sms,
    menu_spam_sms,
    menu_settings;

    menu_search_edittext;
    menu_search_edit_back,
    menu_search_Edittext;

    Listview_Options;
    Listview_back,

    Listview_select_items
    Listview_delete,
    Listview_spam,
    Listview_private;

    */
    SharedPreferences defaultpreferences;
    RelativeLayout Menu, Menu_features, Sms_options, Menu_Search_view;
    RelativeLayout Menu_Search, Menu_Opt_Features, Menu_newcompose,
            Feature_private, Feature_spam, Menu_Settings,
            Search_back,
            Sms_back, Sms_delete, Sms_spam, Sms_private;
    EditText Search_Edittext;
    ImageView more_options_image;
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messages);


         myPackageName = getPackageName();

        compatibleversion=getversion();
      //  System.out.println("this is the version of os "+android.os.Build.VERSION.SDK_INT);
        /*
        * Declarations for the variable of XMl in Messages
        * */

        MessagesOverlay = (RelativeLayout) findViewById(R.id.MessageOverlay);
        MessagesListview = (ListView) findViewById(R.id.MsgListView);
        MessagesListview.setOnItemClickListener(this);
        //AutoHide of keyBoard ..
        MessagesOverlay.setOnTouchListener(this);
        defaultpreferences= PreferenceManager.getDefaultSharedPreferences(getBaseContext());

                 //        MessagesListview.setOnTouchListener(this);
        /*
        * Declarations of All menu Layout here...
        * */
//        ContentValues values = new ContentValues();
//        values.put("address", "8686051460");
//        values.put("body", "hai way2sms via sent db");
//        values.put("type", 6);
//        values.put("date", System.currentTimeMillis());
//        this.getContentResolver().insert(Uri.parse("content://sms/sent"), values);



//                Menu                =(RelativeLayout)findViewById(R.id.MenuLayout_main);
//                Menu_features       =(RelativeLayout)findViewById(R.id.MenuLayout_sub);
//                Sms_options         =(RelativeLayout)findViewById(R.id.Listview_Options);
//                Menu_Search_view    =(RelativeLayout)findViewById(R.id.menu_search_edittext);
//
//                Menu_Search         =(RelativeLayout)findViewById(R.id.menu_search);
//                Menu_Opt_Features   =(RelativeLayout)findViewById(R.id.menu_more_options);
//                more_options_image  =(ImageView)findViewById(R.id.menu_more_options_image);
//                Menu_newcompose     =(RelativeLayout)findViewById(R.id.menu_newcompose);
//                Feature_private     =(RelativeLayout)findViewById(R.id.menu_private_sms);
//                Feature_spam        =(RelativeLayout)findViewById(R.id.menu_spam_sms);
//                Menu_Settings       =(RelativeLayout)findViewById(R.id.menu_settings);
//                Search_back         =(RelativeLayout)findViewById(R.id.menu_search_edit_back);
//                Search_Edittext     =(EditText)findViewById(R.id.menu_search_Edittext);
//                Sms_back            =(RelativeLayout)findViewById(R.id.Listview_back);
//                Sms_delete          =(RelativeLayout)findViewById(R.id.Listview_delete);
//                Sms_spam            =(RelativeLayout)findViewById(R.id.Listview_spam);
//                Sms_private         =(RelativeLayout)findViewById(R.id.Listview_private);



        ActionBar actionBar = getSupportActionBar();
//for color
        actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.AppColor)));

        pd = new ProgressDialog(Messages.this);

        // main layout's declartion
        MenuLayout_main = (RelativeLayout) findViewById(R.id.MenuLayout_main);
        menu_search_edittext = (RelativeLayout) findViewById(R.id.menu_search_edittext);
        menu_search_edittext.setVisibility(View.GONE);
        MenuLayout_sub = (RelativeLayout) findViewById(R.id.MenuLayout_sub);
        Listview_Options = (RelativeLayout) findViewById(R.id.Listview_Options);

        // main menu items
        menu_newcompose = (RelativeLayout) findViewById(R.id.menu_newcompose);
        menu_search = (RelativeLayout) findViewById(R.id.menu_search);
        menu_more_options = (RelativeLayout) findViewById(R.id.menu_more_options);
        menuimage = (ImageView) findViewById(R.id.menu_image);

        // search box instilisation
        menu_search_edit_back = (RelativeLayout) findViewById(R.id.menu_search_edit_back);
        menu_search_edit_back.setOnClickListener(this);
        menu_search_Edittext = (EditText) findViewById(R.id.menu_search_Edittext);
        menu_search_Edittext.addTextChangedListener(this);

        // sub menu item
        menu_private_sms = (RelativeLayout) findViewById(R.id.menu_private_sms);
        menu_spam_sms = (RelativeLayout) findViewById(R.id.menu_spam_sms);
        menu_settings = (RelativeLayout) findViewById(R.id.menu_settings);
        menu_private_sms.setOnClickListener(this);
        menu_spam_sms.setOnClickListener(this);
        menu_settings.setOnClickListener(this);

        // listview item declartion
        Listview_back = (RelativeLayout) findViewById(R.id.Listview_back);
        Listview_delete = (RelativeLayout) findViewById(R.id.Listview_delete);
        Listview_spam = (RelativeLayout) findViewById(R.id.Listview_spam);
        Listview_private = (RelativeLayout) findViewById(R.id.Listview_private);
        Listview_back.setOnClickListener(this);
        Listview_delete.setOnClickListener(this);
        Listview_spam.setOnClickListener(this);
        Listview_private.setOnClickListener(this);


//default layout
        default_aplication=(RelativeLayout)findViewById(R.id.default_aplication);

        default_aplication.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //  String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(Messages.this);
                AlertDialog.Builder builder = new
                        AlertDialog.Builder(Messages.this);
                builder.setMessage(
                       "Way2Inbox is not set as your default messaging app. Do you want to set it default?")
                        .setCancelable(false)
                        .setTitle("Alert!")
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        default_aplication.setVisibility(View.GONE);

                                    }
                                }).setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @TargetApi(19)
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                default_aplication.setVisibility(View.GONE);
                                Intent intent = new Intent(
                                        Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);

                                intent.putExtra(
                                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                        getPackageName());
                                PrintMsg.setLogerror(Messages.this,"Package name is :"+getPackageName());
                                startActivity(intent);

                            }
                        });
                builder.show();
            }
        });
        menu_newcompose.setOnClickListener(this);
        menu_search.setOnClickListener(this);
        menu_more_options.setOnClickListener(this);
        LoadListView();

//        }

    }

    public void LoadListView(){
        helper = new Native_DatabaseHelper(this);
        allsms = helper.getAllsms(1,null);

        MessageList = (ListView) findViewById(R.id.MsgListView);

        MessageList.setChoiceMode(MessageList.CHOICE_MODE_MULTIPLE_MODAL);

        listAdapter = new myadapter((ArrayList<smsfetch>) allsms);
        MessageList.setAdapter(listAdapter);
        MessageList.setOnItemClickListener(this);
    }
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean getdefaultpackage(){


        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName))
        {
            return false;
        }else{
        return true;
        }
    }
    public boolean getversion(){


        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= Build.VERSION_CODES.KITKAT){
            return true;

        }else{

        }return false;
    }
    @Override
    public void onResume(){
    super.onResume();
    LoadListView();
    if(getversion()) {
        if (!getdefaultpackage()) {
            default_aplication.setVisibility(View.VISIBLE);
        }
    }
}



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.menu_messages, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.Default_sms) {

//                if (android.os.Build.VERSION.RELEASE.contains("4.4")) {
//                    PrintMsg.SetToast(Messages.this,"Supported",1);
//                    Intent intent = new Intent(
//                            Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
//                    intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
//                    startActivity(intent);
//                }else{
//                    PrintMsg.SetToast(Messages.this,"Sorry No Support",1);
//                }


           String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(this);
            final String myPackageName = getPackageName();

            if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName))
            {
                // App is not default.
                // Show the "not currently set as the default SMS app" interface
                // Set up a button that allows the user to change the default SMS
                // app

                        Intent intent = new Intent(
                                Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                        intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                myPackageName);
                        startActivity(intent);

            } else {
                // App is the default.
                // Hide the "not currently set as the default SMS app" interface
                PrintMsg.SetToast(Messages.this, "App is already set to Default", 1);
            }

            if (android.os.Build.VERSION.RELEASE.contains("4.4")) {

                if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName))
                {

                    // App is not default.
                    // Show the "not currently set as the default SMS app" interface

                    AlertDialog.Builder builder = new
                            AlertDialog.Builder(Messages.this);
                    builder.setMessage(
                            defaultSmsApp+" is not set as your default messaging app. Do you want to set it default?")
                            .setCancelable(false)
                            .setTitle("Alert!")
                            .setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {

                                        }
                                    }).setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                @TargetApi(19)
                                public void onClick(DialogInterface dialog,
                                                    int id) {

                                    Intent intent = new Intent(
                                            Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);

                                    intent.putExtra(
                                            Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,
                                            getPackageName());
                                    PrintMsg.setLogerror(Messages.this,"Package name is :"+getPackageName());
                                    startActivity(intent);

                                }
                            });
                    builder.show();

                }

            }else{
                PrintMsg.SetToast(Messages.this,"Default SMS not supported",0);
            }


            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.
                INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }

    class myadapter extends BaseAdapter implements Filterable {
        ArrayList<smsfetch> con_list;
        SparseBooleanArray mSparseBooleanArray;
        private SparseBooleanArray mSelectedItemsIds;
        public myadapter(ArrayList<smsfetch> con_list) {
            this.con_list = con_list;
            orinalConlist = con_list;
            mSparseBooleanArray = new SparseBooleanArray();
        }

        public ArrayList<String> getCheckedItems() {
            ArrayList<String> mTempArry = new ArrayList<String>();

            for(int i=0;i<con_list.size();i++) {
                if(mSparseBooleanArray.get(i)) {
                    smsfetch fetch=con_list.get(i);
                    mTempArry.add(fetch.getAddress());
                }
            }
            System.out.println("this is original size "+mTempArry.size());
            return mTempArry;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return con_list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return con_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            holder viewHolder;
            View v = convertView;
            if (convertView == null) {
                LayoutInflater li = (LayoutInflater) Messages.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = li.inflate(R.layout.adapter_all_messages, null);
                viewHolder = new holder();
                v.setTag(viewHolder);
            } else {
                viewHolder = (holder) v.getTag();
            }
            viewHolder.name = (TextView) v.findViewById(R.id.sms_name);
            viewHolder.lt_msg = (TextView) v.findViewById(R.id.sms_msg);
            viewHolder.cl_pid = (TextView) v.findViewById(R.id.cl_pid);
            viewHolder.sms_image=(ImageView)v.findViewById(R.id.sms_image);
            viewHolder.imagecheck=(CheckBox)v.findViewById(R.id.checkbox);
            viewHolder.imagecheck.setTag(position);
            viewHolder.imagecheck.setChecked(mSparseBooleanArray.get(position));
            viewHolder.imagecheck.setOnCheckedChangeListener(mCheckedChangeListener);
            if(viewHolder.imagecheck.isChecked()){
                viewHolder.sms_image.setImageResource(R.drawable.user_check);
            }else{
                viewHolder.sms_image.setImageResource(R.drawable.noimage_male);
            }

            smsfetch model = con_list.get(position);
//            Log.e("Messages : ", "----" + model.getAddress() + "----" + model.getReadState());
            if(model.getReadState().equalsIgnoreCase("0")){
                //UNREAD MESSAGE ARE SHOWN HERE..
                viewHolder.name.setTypeface(null, Typeface.BOLD);
                viewHolder.lt_msg.setTypeface(null, Typeface.BOLD);
                viewHolder.lt_msg.setTextColor(getResources().getColor(R.color.Black));


            }else {
                //READ MESSAGE ARE SHOWN HERE
                viewHolder.name.setTypeface(null, Typeface.NORMAL);
                viewHolder.lt_msg.setTypeface(null, Typeface.NORMAL);
                viewHolder.lt_msg.setTextColor(getResources().getColor(R.color.light_black));
            }




            viewHolder.cl_pid.setText(model.getAddress());

//            if(model.getAddress().contains("-WAYSMS")){
//
//            }
//            String name = model.getAddress();
//            if (name.equals(null)) {
                viewHolder.name.setText(model.get_person());
//            } else {
//                viewHolder.name.setText(model.getAddress());
//            }
            viewHolder.lt_msg.setText(model.getMsg());
            //viewHolder.sms_image.setOnClickListener(l);
            // viewHolder.date.setText(model.getTime());
            //viewHolder.sms_image.setImageResource(R.drawable.user);
            if(mSparseBooleanArray.get(position)){
                viewHolder.sms_image.setImageResource(R.drawable.user_check);
            }else{
                viewHolder.sms_image.setImageResource(R.drawable.noimage_male);
            }
//            System.out.println(model.get_person() + "  " + model.get_seen()
//                    + "   " + model.getReadState());
            return v;
        }
        public List<smsfetch> getWorldPopulation() {
            return con_list;
        }

        public void toggleSelection(int position) {
            selectView(position, !mSelectedItemsIds.get(position));
        }

        public void removeSelection() {
            mSparseBooleanArray = new SparseBooleanArray();
            notifyDataSetChanged();
        }

        public void selectView(int position, boolean value) {
            if (value)
                mSelectedItemsIds.put(position, value);
            else
                mSelectedItemsIds.delete(position);
            notifyDataSetChanged();
        }

        public int getSelectedCount() {
            return mSelectedItemsIds.size();
        }

        public SparseBooleanArray getSelectedIds() {
            return mSelectedItemsIds;
        }
        @Override
        public Filter getFilter() {
            if (contactFilter == null)
                contactFilter = new ContactFilter();
            return contactFilter;
        }

        public void resetData() {
            con_list = orinalConlist;
        }

        private class ContactFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                // We implement here the filter logic
                if (constraint == null || constraint.length() == 0) {
                    // No filter implemented we return all the list
                    results.values = orinalConlist;
                    results.count = orinalConlist.size();
                } else {
                    // We perform filtering operation
                    List<smsfetch> nPlanetList = new ArrayList<smsfetch>();
                    for (smsfetch p : con_list) {

                        //SEARCHING BY NAME OR NUMBER..
                        if (p.getAddress()
                                .toUpperCase()
                                .startsWith(constraint.toString().toUpperCase())) {
                            nPlanetList.add(p);
                        }

                        //SEARCHING BY MESSAGE
                        if(p.getMsg().toUpperCase().contains(constraint.toString().toUpperCase())){
                            nPlanetList.add(p);
                        }

                    }
                    results.values = nPlanetList;
                    results.count = nPlanetList.size();
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0)
                    notifyDataSetInvalidated();
                else {
                    con_list = (ArrayList<smsfetch>) (List<smsfetch>) results.values;
                    notifyDataSetChanged();
                }
            }
        }
        CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
                notifyDataSetChanged();
                MessageList.setStackFromBottom(true);

                if(getCheckedItems().size()==0){
                    MenuLayout_main.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }else {

                    if (MenuLayout_main.getVisibility() == View.VISIBLE) {
                        MenuLayout_main.setVisibility(View.INVISIBLE);
                        Listview_Options.setVisibility(View.VISIBLE);
                    }
                }

            }
        };
    }

    class holder {

        public TextView name;
        public TextView lt_msg;
        public TextView date, cl_pid;
        public ImageView sms_image;

        public CheckBox imagecheck;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        //smsfetch model=allsms.get(position);
        // smslist
        // =(ArrayList<smsfetch>)sms.getAllSms(Messages.this,"Inbox","Single",model.getAddress());
        // for (int i = 0; i < smslist.size(); i++) {
        // smsfetch model1=smslist.get(i);
        // System.out.println(model.getMsg()+"---"+model.get_person()+"---"+model.getAddress());
        //
        // }
        PrintMsg.SetToast(Messages.this,"ItemClicked",0);
        TextView tv = (TextView) view.findViewById(R.id.cl_pid);
        TextView tv1=(TextView)view.findViewById(R.id.sms_name);
        Intent i = new Intent(this, ComposeSmsActivity.class);
        i.putExtra("MobileNo", tv.getText().toString());
        if(tv.getText().toString().equals(tv1.getText().toString())){
            i.putExtra("MobileName","NONE");
        }else{
            i.putExtra("MobileName", tv1.getText().toString());}
        startActivity(i);
        finish();

    }



    public String getContactName(String phoneNumber) {
        ContentResolver cr = this.getContentResolver();
        Uri uri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNumber));
        Cursor cursor = cr.query(uri,
                new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME },
                null, null, null);
        if (cursor == null) {
            return null;
        }
        String contactName = null;
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        } else {
            contactName = phoneNumber;
        }

        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }

        return contactName;
    }




    ArrayList<smsfetch> SpamSMS,PrivateSMS;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_search:
                MenuLayout_main.setVisibility(View.INVISIBLE);
                menu_search_edittext.setVisibility(View.VISIBLE);
                if (MenuLayout_sub.getVisibility() == View.VISIBLE) {
                    MenuLayout_sub.setVisibility(View.GONE);
                }

                break;
            case R.id.menu_newcompose:
                startActivity(new Intent(this, Contacts.class));

                break;

            case R.id.menu_more_options:

                if (MenuLayout_sub.getVisibility() == View.VISIBLE) {
                    MenuLayout_sub.setVisibility(View.GONE);
                    menuimage.setImageResource(R.drawable.menu);
                    if(getversion()){
                        if(!getdefaultpackage() ){
                        default_aplication.setVisibility(View.VISIBLE);
                    }
                                   }

                } else {
                    MenuLayout_sub.setVisibility(View.VISIBLE);
                    menuimage.setImageResource(R.drawable.down);
                    default_aplication.setVisibility(View.GONE);
                }
                break;


            case R.id.menu_search_edit_back:

                menu_search_Edittext.setText("");
                MenuLayout_main.setVisibility(View.VISIBLE);
                menu_search_edittext.setVisibility(View.GONE);


                break;


            case R.id.menu_private_sms:
//                ArrayList<String> checkedprivate=listAdapter.getCheckedItems();
//                System.out.println("selected size"+checkedprivate.size());
//                for (int i = 0; i < checkedprivate.size(); i++) {
//                    System.out.println("selected address "+checkedprivate.get(i));
//                    helper.insertPrivate_Spam(checkedprivate.get(i),2);
//                }
//
//                ArrayList<String> private_sms=helper.getPrivate_spam(2);
//                PrivateSMS=(ArrayList<smsfetch>) helper.getAllsms(3,"");
//                listAdapter = new myadapter(PrivateSMS);
//                MessageList.setAdapter(listAdapter);
//
//                Listview_Options.setVisibility(View.GONE);
                MenuLayout_main.setVisibility(View.VISIBLE);
                MenuLayout_sub.setVisibility(View.GONE);
                String passwordstatus=defaultpreferences.getString(
                        ApplicationConstants.SettingsPreferenceKeys.PASSWORD,
                        "disabled");
                String password=defaultpreferences.getString("passwordvalue",null);
                if(passwordstatus.equals("enabled")){
if(password.equals(null)){
    d=new Dialog(this);
    d.setTitle("password");
    d.setContentView(R.layout.dialog);
    final EditText oldpassword=(EditText)d.findViewById(R.id.old_password);
    oldpassword.setVisibility(View.GONE);
    final EditText newpassword=(EditText)d.findViewById(R.id.new_password);
    final EditText re_password=(EditText)d.findViewById(R.id.Re_password);
    Button ok=(Button)d.findViewById(R.id.ok);
    Button cancel=(Button)d.findViewById(R.id.cancel);
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String password=newpassword.getText().toString();
            String re_password1=re_password.getText().toString();
            if(password.equals(re_password1)){
                insertpassword(password);
                Toast.makeText(Messages.this, "password enabled", Toast.LENGTH_SHORT).show();
                changePreference("enabled");
                d.cancel();
            }else{
                Toast.makeText(Messages.this, "password mismatch", Toast.LENGTH_SHORT).show();

            }

        }
    });
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            d.cancel();
        }
    });
    d.show();
}else{
    d=new Dialog(this);
    d.setTitle("password");
    d.setContentView(R.layout.dialog);
    final EditText oldpassword=(EditText)d.findViewById(R.id.old_password);
    oldpassword.setVisibility(View.GONE);
    final EditText newpassword=(EditText)d.findViewById(R.id.new_password);
    final EditText re_password=(EditText)d.findViewById(R.id.Re_password);
    re_password.setVisibility(View.GONE);
    Button ok=(Button)d.findViewById(R.id.ok);
    Button cancel=(Button)d.findViewById(R.id.cancel);
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String password=defaultpreferences.getString("passwordvalue",null);
            String password1=newpassword.getText().toString();
            if(password1.equals(password)){
                // insertpassword(password);
                startActivity(new Intent(Messages.this, PrivateSMS.class));
                overridePendingTransition(0, 0);
                finish();
                d.cancel();
            }else{
                Toast.makeText(Messages.this,"password mismatch",Toast.LENGTH_SHORT).show();

            }

        }
    });
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            d.cancel();
        }
    });
    d.show();

}
                }else{
                    startActivity(new Intent(this, PrivateSMS.class));
                    overridePendingTransition(0, 0);
                    finish();
                }



                break;


            case R.id.menu_spam_sms:
//                ArrayList<String> checkedspam=listAdapter.getCheckedItems();
//                System.out.println("selected size"+checkedspam.size());
//                for (int i = 0; i < checkedspam.size(); i++) {
//                    System.out.println("selected address "+checkedspam.get(i));
//                    helper.insertPrivate_Spam(checkedspam.get(i),1);
//                }
//
//                ArrayList<String>spam_sms=helper.getPrivate_spam(1);
//
//                SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(2,"");
//                listAdapter = new myadapter(SpamSMS);
//                MessageList.setAdapter(listAdapter);
//
//
//                MenuLayout_main.setVisibility(View.VISIBLE);
//                Listview_Options.setVisibility(View.GONE);
                MenuLayout_sub.setVisibility(View.GONE);
                MenuLayout_main.setVisibility(View.VISIBLE);

                startActivity(new Intent(this, SpamSMS.class));
                overridePendingTransition(0, 0);
                finish();
                break;


            case R.id.menu_settings:

                startActivity(new Intent(this, SettingsHeaderActivity.class));
                overridePendingTransition(0, 0);
                finish();

                break;


            case R.id.Listview_back:
                System.out.println("back is selected");
                MenuLayout_main.setVisibility(View.VISIBLE);
                Listview_Options.setVisibility(View.GONE);
                listAdapter.removeSelection();

                break;



            case R.id.Listview_delete:
                ArrayList<String> list = listAdapter.getCheckedItems();
                MenuLayout_main.setVisibility(View.VISIBLE);
                Listview_Options.setVisibility(View.GONE);
                Uri deleteUri = Uri.parse("content://sms");
                for (int i = 0; i < list.size(); i++) {

                    Messages.this.getContentResolver().delete(deleteUri,
                            "address= ?", new String[] { list.get(i) });
                    System.out.println("selected address " + list.get(i));
                }
                SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(1,"");
                listAdapter = new myadapter(SpamSMS);
                MessageList.setAdapter(listAdapter);

                break;


            case R.id.Listview_spam:
                ArrayList<String> spamlist=listAdapter.getCheckedItems();
                if(spamlist.size()==0){
                    PrintMsg.SetToast(this, getResources().getString(R.string.Listview_opt_spam), 1);
                }else{
                    for (int i = 0; i < spamlist.size(); i++) {
                        helper.insertPrivate_Spam(spamlist.get(i), 1);
                    }

                     SpamSMS=(ArrayList<smsfetch>) helper.getAllsms(1,"");
                    listAdapter = new myadapter(SpamSMS);
                    MessageList.setAdapter(listAdapter);

                    MenuLayout_main.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }


                break;
            case R.id.Listview_private:
                ArrayList<String> privatelist=listAdapter.getCheckedItems();
                PrintMsg.setLogerror(Messages.this,"Private Size list :"+privatelist.size());
                if(privatelist.size()==0){
                    PrintMsg.SetToast(this, getResources().getString(R.string.Listview_opt_private), 1);
                }else{
                    for (int i = 0; i < privatelist.size(); i++) {
                        helper.insertPrivate_Spam(privatelist.get(i), 2);
                    }

                    PrivateSMS=(ArrayList<smsfetch>) helper.getAllsms(1,"");
                    listAdapter = new myadapter(PrivateSMS);
                    MessageList.setAdapter(listAdapter);

                    MenuLayout_main.setVisibility(View.VISIBLE);
                    Listview_Options.setVisibility(View.GONE);
                }
                break;



            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (count < before) {
            // We're deleting char so we need to reset the adapter data
            listAdapter.resetData();
        }
        listAdapter.getFilter().filter(s.toString());

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }


    private Boolean doubleBackToExitPressedOnce=false,st1=false;
    int backI=0;
    @Override
    public void onBackPressed() {



            if (doubleBackToExitPressedOnce) {
                super.onBackPressed();
                return;
            }

            this.doubleBackToExitPressedOnce = true;
        PrintMsg.SetToast(this,"Please click again to exit",1);


            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce=false;
                }
            }, 2000);
        }



    @Override
    public void onStart(){
        super.onStart();
        listAdapter.notifyDataSetChanged();
        LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver), new IntentFilter(Constants.FILTER));
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("KBR", "Got message");
            handleMessage(intent);
        }
    };
    private void handleMessage(Intent msg)
    {
        Bundle data = msg.getExtras();
        switch (data.getInt(Constants.COMMAND, 0))
        {
            case Constants.UPDATE_PROGRESS:
                int progress = data.getInt(Constants.DATA, 0);
                if(progress==3) {
                    LoadListView();
                }

                break;

            default:
                break;
        }
    }
    public void insertpassword(String password){
        SharedPreferences.Editor ed=defaultpreferences.edit();
        ed.putString("passwordvalue",password);
        ed.commit();
        Toast.makeText(this,"password set succesfully",Toast.LENGTH_SHORT).show();
    }
    public void changePreference(String status){
        SharedPreferences.Editor ed=defaultpreferences.edit();
        ed.putString(ApplicationConstants.SettingsPreferenceKeys.PASSWORD,status);
        ed.commit();
    }
}
